﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using DataScripter.Scripting.ProcessDefinitions;
using DataScripter.Scripting.Processes;
using DataScripter.Scripting.Processes.Output;
using DataScripter.XmlInterpreter;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace DataScripter.Tasks
{
    public class TruncateTablesTask : Task
    {

        [Required]
        public string Database { get; set; }
        [Required]
        public string Server { get; set; }
        [Required]
        public ITaskItem[] Tables { get; set; }
        [Output]
        public string Output { get; set; }
        public Boolean Quiet { get; set; }

        public override bool Execute()
        {
            XmlDocument xmlFile = GetResourceXmlFile("Script.TruncateTables.xml");

            string constring = string.Format("Data Source={0};Initial Catalog={1};Integrated Security=True", Server, Database);
            xmlFile.GetElementsByTagName("ConnectionString")[0].InnerText = constring;

            foreach (ITaskItem table in Tables)
            {
                XmlElement elem = xmlFile.CreateElement("Table");
                XmlAttribute attr = xmlFile.CreateAttribute("Name");
                attr.InnerText = table.ItemSpec;
                elem.Attributes.Append(attr);
                xmlFile.GetElementsByTagName("TableList")[0].AppendChild(elem);
            }

            XmlEngineConfiguration configuration = new XmlEngineConfiguration(xmlFile.InnerXml);
            configuration.Run();
            Output = ((TextProcessOutput)configuration.Engine.Resolve<IProcessDefinition>().Output).Text;
            if (!Quiet) Log.LogMessage(Output);

            return !Log.HasLoggedErrors;
        }
        public XmlDocument GetResourceXmlFile(string filename)
        {
            XmlDocument xdoc = new XmlDocument();
            using (Stream stream = this.GetType().Assembly.GetManifestResourceStream("DataScripter.Tasks."+filename))
            using (StreamReader sr = new StreamReader(stream))
                xdoc.LoadXml(sr.ReadToEnd());
            return xdoc;
        }
    }
}
